package com.industrial.premu.controller;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.extra.template.TemplateException;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.industrial.common.core.domain.R;
import com.industrial.common.core.utils.StringUtils;
import com.industrial.common.core.utils.poi.ExcelUtil;
import com.industrial.common.core.utils.uuid.IdUtils;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.premu.domain.*;
import com.industrial.premu.domain.sqsj.*;
import com.industrial.premu.dto.PreMuAppealDto;
import com.industrial.premu.dto.PreMuBenefitEvaluationDto;
import com.industrial.premu.dto.PreMuChartsDto;
import com.industrial.premu.mapper.*;
import com.industrial.premu.mapper.sqsj.*;
import com.industrial.premu.service.*;
import com.industrial.premu.service.impl.PreMuBenefitEvaluationService2025;
import com.industrial.premu.util.FreemarkerUtils;
import com.industrial.premu.vo.*;
import com.industrial.system.api.RemoteWhiteInfoService;
import com.industrial.system.api.RemoteUserService;
import com.industrial.system.api.domain.EmEnterpriseInformationCollection;
import com.industrial.system.api.domain.SysUser;
import com.industrial.system.api.model.LoginUser;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.industrial.common.log.annotation.Log;
import com.industrial.common.log.enums.BusinessType;
import com.industrial.common.security.annotation.RequiresPermissions;
import com.industrial.common.core.web.controller.BaseController;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.core.web.page.TableDataInfo;

import java.io.IOException;
import java.util.List;
/**
 * 亩产效益评价Controller
 *
 * @author ZHOU_S
 * @date 2024-01-25
 */
@RestController
@RequestMapping("/evaluation")
public class PreMuBenefitEvaluationController extends BaseController
{
    @Autowired
    private IPreMuBenefitEvaluationService preMuBenefitEvaluationService;
    @Autowired
    private PreMuBenefitEvaluationService2025 preMuBenefitEvaluationService2025;
    @Autowired
    private IPreMuBenefitEvaluationAppealService preMuBenefitEvaluationAppealService;
    @Autowired
    private IPreMuBenefitEvaluationAppealDetailsService preMuBenefitEvaluationAppealDetailsService;
    @Autowired
    private FreemarkerUtils FreemarkerUtil;
    @Autowired
    private IPreMuCustomIndicatorService preMuCustomIndicatorService;
    @Autowired
    private PreMuImportAddMapper preMuImportAddMapper;
    @Autowired
    private PreMuImportAddSubstractMapper preMuImportAddSubstractMapper;
    @Autowired
    private IPreMuRejectService preMuRejectService;

    @Autowired
    private PreMuImportBenefitEvaluationNoMapper preMuImportBenefitEvaluationNoMapper;

    @Autowired
    PreMuImportVetoMapper preMuImportVetoMapper;

    @Autowired
    private PreMuImportSubstractMapper preMuImportSubstractMapper;

    @Autowired
    private PreMuImportCustomIndexLjMapper preMuImportCustomIndexLjMapper;

    @Autowired
    private PreMuBenefitEvaluationMapper preMuBenefitEvaluationMapper;

    @Autowired
    private RemoteWhiteInfoService remoteWhiteInfoService;

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private PreMuBenefitEvaluationNoMapper preMuBenefitEvaluationNoMapper;
    @Autowired
    private IPreMuExportCountsService preMuExportCountsService;

    @Autowired
    private SysAreaMapper sysAreaMapper;

    @Autowired
    private IPreMuCompanyInfoService preMuCompanyInfoService;
    @Autowired
    private IPreMuImportAddSubstractService preMuImportAddSubstractService;
    @Autowired
    private IPremuPasswordService premuPassWordService;
    @Autowired
    private PreMuBenefitEvaluationMapper2025 preMuBenefitEvaluationMapper2025;

    /**
     * 将亩产中的信息保存到白名单中
     * @return
     */
    @GetMapping("/addPreMuToWhite/{uscc}")
    public AjaxResult addPreMuToWhite(@PathVariable("uscc") String uscc){
        //查询亩产中的企业信息
        PreMuCompanyInfo companyInfo = preMuCompanyInfoService.selectPreMuCompanyInfoByUscc(uscc);
        Map<String, Object> companyInfoMap = BeanUtil.beanToMap(companyInfo);

        R<Boolean> booleanR = remoteWhiteInfoService.savePreMuCompanyInfoToWhite(companyInfoMap);
        if(booleanR.getCode() == R.SUCCESS){
            if(booleanR.getData()){
                //给此用户写入白名单的普通角色
                SysUser sysUserRole = new SysUser();
                sysUserRole.setUserId(SecurityUtils.getUserId());
                sysUserRole.setRoleId("a232ec59dab040aaabfce8b4a0eba3f7");
                remoteUserService.insertUserRole(sysUserRole);
                return AjaxResult.success("保存成功");
            }else{
                return AjaxResult.warn("保存失败");
            }
        }
        return AjaxResult.warn("保存失败");
    }


    /**
     * 查询是否在白名单中存在
     * @param uscc
     * @return
     */
    @GetMapping("/queryExistWhite/{uscc}")
    public AjaxResult queryExistWhite(@PathVariable("uscc") String uscc){
        R<Boolean> booleanR = remoteWhiteInfoService.preMuExistWhite(uscc);
        if(booleanR.getCode() == R.SUCCESS){
            return booleanR.getData() ? AjaxResult.success(true) : AjaxResult.warn("当前企业已申请过白名单");
        }
        throw new RuntimeException("信息查询异常");
    }

    /**
     * 查询亩产效益评价列表
     */
    @RequiresPermissions("premu:evaluation:list")
    @GetMapping("/list")
    public TableDataInfo list(PreMuBenefitEvaluation preMuBenefitEvaluation)
    {
        List<PreMuBenefitEvaluation> list=new ArrayList<>();
        //如果不是数据，说明是在亩产大屏里面跳转过来的
        if(org.apache.commons.lang3.StringUtils.isNotBlank(preMuBenefitEvaluation.getCity()) && !NumberUtil.isNumber(preMuBenefitEvaluation.getCity())){
            String cityCode = sysAreaMapper.selectCodeByAreaName(preMuBenefitEvaluation.getCity());
            preMuBenefitEvaluation.setCity(cityCode);
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Set<String> roles= loginUser.getRoles();
        if(roles.contains("q_01_001")){
            preMuBenefitEvaluation.setUscc(loginUser.getUsername());
        }
        startPage();
        if(preMuBenefitEvaluation!=null){
            if(StringUtils.isNotNull(preMuBenefitEvaluation.getDataType())){
                    if("1".equals(preMuBenefitEvaluation.getDataType())){
                        list= preMuBenefitEvaluationService.selectPreMuBenefitEvaluationList(preMuBenefitEvaluation);
                        if(list!=null&&list.size()>0) {
                            for (PreMuBenefitEvaluation p : list) {
                                p.setDataType("1");
                            }
                        }
                    }else if("2".equals(preMuBenefitEvaluation.getDataType())){
                            list=preMuBenefitEvaluationNoMapper.selectNoList(preMuBenefitEvaluation);
                        if(list!=null&&list.size()>0) {
                        for (PreMuBenefitEvaluation p:list) {
                            p.setDataType("2");
                        }
                    }
                    }
            }else{
                preMuBenefitEvaluation.setDataType("1");
                list= preMuBenefitEvaluationService.selectPreMuBenefitEvaluationList(preMuBenefitEvaluation);
                if(list!=null&&list.size()>0){
                    for (PreMuBenefitEvaluation p:list) {
                        p.setDataType("1");
                    }
                }

            }
        }
        return getDataTable(list);
    }

    /**
     * 导出亩产效益评价列表
     */


    @RequiresPermissions("premu:evaluation:export")
    @Log(title = "亩产效益评价", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public String  export(HttpServletResponse response, PreMuBenefitEvaluation preMuBenefitEvaluation) throws UnsupportedEncodingException {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            Set<String> roles= loginUser.getRoles();
            String companyType="";
            String area="";
            // 尝试执行的代码块
            if(roles.contains("x_01_011")||roles.contains("along_yellow_river")||roles.contains("s_01_011")){
                PreMuExportCounts preMuExportCounts= preMuExportCountsService.selectOne(loginUser.getUserid());
                if(preMuExportCounts!=null){
//                    if(preMuExportCounts.getCounts().contains("6")){
//                        return  "导出次数已达到上限！";
//                    }else {
//                        int counts=  Integer.valueOf(preMuExportCounts.getCounts())+1;
//                        preMuExportCounts.setCounts(String.valueOf(counts));
//                        preMuExportCountsService.updatePreMuExportCounts(preMuExportCounts);
//                    }
                    int counts=  Integer.valueOf(preMuExportCounts.getCounts())+1;
                    preMuExportCounts.setCounts(String.valueOf(counts));
                    preMuExportCountsService.updatePreMuExportCounts(preMuExportCounts);

                }else{
                    preMuExportCounts=new PreMuExportCounts();
                    preMuExportCounts.setBaseId(IdUtil.simpleUUID());
                    preMuExportCounts.setUserId(loginUser.getUserid());
                    preMuExportCounts.setCounts("1");
                    preMuExportCountsService.addPreMuExportCounts(preMuExportCounts);
                }

            }
            /*  if(preMuBenefitEvaluation!=null){*/
            /* if(preMuBenefitEvaluation.getPremuPassWord()!=null){*/
                 /*   PreMuPassword preMuPassword=  premuPassWordService.getbyPassWord(preMuBenefitEvaluation.getPremuPassWord());
                    if(preMuPassword!=null){*/
            if(roles.contains("q_01_001")){
                preMuBenefitEvaluation.setUscc(loginUser.getUsername());
            }else if(roles.contains("x_01_011")||roles.contains("along_yellow_river")){
                String county=  loginUser.getSysUser().getDistrict();
                preMuBenefitEvaluation.setCounty(county);
             area=   sysAreaMapper.selectAreaNameByCode(county);
            }else if(roles.contains("s_01_011")){
                String city=  loginUser.getSysUser().getCity();
                preMuBenefitEvaluation.setCity(city);
                preMuBenefitEvaluation.setStatus("5");
                area=   sysAreaMapper.selectAreaNameByCode(city);
            }else if(roles.contains("p_01_011")){
                String province=  loginUser.getSysUser().getProvince();
                preMuBenefitEvaluation.setProvince(province);
                preMuBenefitEvaluation.setStatus("5");
                area=   sysAreaMapper.selectAreaNameByCode(province);
            }
            // 设置响应内容类型
            response.setContentType("application/vnd.ms-excel");
            // 设置响应头，指定文件名
            if(StringUtils.isNotNull(preMuBenefitEvaluation.getCompanyType())){
                if(preMuBenefitEvaluation.getCompanyType().contains("1")){
                    companyType="规上企业";
                }else{
                    companyType="规下企业";
                }
            }
            String filename = preMuBenefitEvaluation.getYears()+"年"+area+""+companyType+"亩产效益数据采集情况.xlsx";
            response.setHeader("Content-Disposition", "attachment; filename=\"" +
                    new String(filename.getBytes("UTF-8"), "ISO-8859-1") + "\"");
            if(StringUtils.isNotNull(preMuBenefitEvaluation.getExportType())){
                if("1".contains(preMuBenefitEvaluation.getExportType())){
                    if(this.before2024Year(preMuBenefitEvaluation.getYears())) {
                        List<PreMuBenefitEvaluationVo>  list = preMuBenefitEvaluationService.getExportList(preMuBenefitEvaluation);
                        ExcelUtil<PreMuBenefitEvaluationVo> util = new ExcelUtil<PreMuBenefitEvaluationVo>(PreMuBenefitEvaluationVo.class);
                        util.exportExcel(response, list, preMuBenefitEvaluation.getYears()+"年"+area+""+companyType+"亩产效益评价数据","按地市导出");
                    }else {
                        List<PreMuBenefitEvaluation20250520Vo>  list = preMuBenefitEvaluationService.getExportList2025(preMuBenefitEvaluation);
                        ExcelUtil<PreMuBenefitEvaluation20250520Vo> util = new ExcelUtil<>(PreMuBenefitEvaluation20250520Vo.class);
                        util.exportExcel(response, list, preMuBenefitEvaluation.getYears()+"年"+area+""+companyType+"亩产效益评价数据","按地市导出");
                    }
                }else if("2".contains(preMuBenefitEvaluation.getExportType())){
                    if(this.before2024Year(preMuBenefitEvaluation.getYears())) {
                        List<PreMuLevelBenefitEvaluationVo> list = preMuBenefitEvaluationService.getExportListGroupLevel(preMuBenefitEvaluation);
                        ExcelUtil<PreMuLevelBenefitEvaluationVo> util = new ExcelUtil<PreMuLevelBenefitEvaluationVo>(PreMuLevelBenefitEvaluationVo.class);
                        util.exportExcel(response, list, preMuBenefitEvaluation.getYears()+"年"+area+""+companyType+"亩产效益评价数据","按评级导出");
                    }
                    else {
                        List<PreMuLevelBenefitEvaluationVo20250520> list = preMuBenefitEvaluationService.getExportListGroupLevel2025(preMuBenefitEvaluation);
                        ExcelUtil<PreMuLevelBenefitEvaluationVo20250520> util = new ExcelUtil<PreMuLevelBenefitEvaluationVo20250520>(PreMuLevelBenefitEvaluationVo20250520.class);
                        util.exportExcel(response, list, preMuBenefitEvaluation.getYears()+"年"+area+""+companyType+"亩产效益评价数据","按评级导出");
                    }

                }else if("3".contains(preMuBenefitEvaluation.getExportType())){
                    if(this.before2024Year(preMuBenefitEvaluation.getYears())) {
                        List<PreMuIndustryBenefitEvaluationVo>   list = preMuBenefitEvaluationService.getExportListGroupIndustry(preMuBenefitEvaluation);
                        ExcelUtil<PreMuIndustryBenefitEvaluationVo> util = new ExcelUtil<PreMuIndustryBenefitEvaluationVo>(PreMuIndustryBenefitEvaluationVo.class);
                        util.exportExcel(response, list, preMuBenefitEvaluation.getYears()+"年"+area+""+companyType+"亩产效益评价数据","导出按行业");
                    }
                    else {
                        List<PreMuIndustryBenefitEvaluationVo20250520>   list = preMuBenefitEvaluationService.getExportListGroupIndustry2025(preMuBenefitEvaluation);
                        ExcelUtil<PreMuIndustryBenefitEvaluationVo20250520> util = new ExcelUtil<>(PreMuIndustryBenefitEvaluationVo20250520.class);
                        util.exportExcel(response, list, preMuBenefitEvaluation.getYears()+"年"+area+""+companyType+"亩产效益评价数据","导出按行业");
                    }

                }else if("4".contains(preMuBenefitEvaluation.getExportType())){
                    // 获取响应输出流
                    preMuBenefitEvaluationService.getExcel(response);
                }
            } else{
                if(this.before2024Year(preMuBenefitEvaluation.getYears())) {
                    List<PreMuLevelBenefitEvaluationVo> list = preMuBenefitEvaluationService.getExportListGroupLevel(preMuBenefitEvaluation);
                    ExcelUtil<PreMuLevelBenefitEvaluationVo> util = new ExcelUtil<PreMuLevelBenefitEvaluationVo>(PreMuLevelBenefitEvaluationVo.class);
                    util.exportExcel(response, list, preMuBenefitEvaluation.getYears()+"年"+area+""+companyType+"亩产效益评价数据",preMuBenefitEvaluation.getYears()+"年"+area+""+companyType+"亩产效益评价数据");
                }
                else {
                    List<PreMuLevelBenefitEvaluationVo20250520> list = preMuBenefitEvaluationService.getExportListGroupLevel2025(preMuBenefitEvaluation);
                    ExcelUtil<PreMuLevelBenefitEvaluationVo20250520> util = new ExcelUtil<PreMuLevelBenefitEvaluationVo20250520>(PreMuLevelBenefitEvaluationVo20250520.class);
                    util.exportExcel(response, list, preMuBenefitEvaluation.getYears()+"年"+area+""+companyType+"亩产效益评价数据",preMuBenefitEvaluation.getYears()+"年"+area+""+companyType+"亩产效益评价数据");
                }
            }

                   /* }else{
                        return  warn("密码错误！");
                    }*/
               /* }else{
                    return  warn("请输入密码!");
                }*/
           /* }else{
                return  warn("密码错误！");
            }*/

            return "导出成功";
        }catch (Exception e){
            e.printStackTrace();
            return  "导出异常！";
        }
    }


    /**     * 获取亩产效益评价详细信息

     *  private List<PremuImportAddSubstractVo> addList;
     *     private List<PremuImportAddSubstractVo> subList;
     */
    @RequiresPermissions("premu:evaluation:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {

        PreMuBenefitEvaluationVo preMuBenefitEvaluationVo =  preMuBenefitEvaluationService.getById(id);
        if(preMuBenefitEvaluationVo!=null){

        }else{
            preMuBenefitEvaluationVo=preMuBenefitEvaluationNoMapper.getById(id);
        }
        //加分
        preMuBenefitEvaluationVo.setAddList(preMuImportAddMapper.getUscc(preMuBenefitEvaluationVo.getUscc(),preMuBenefitEvaluationVo.getYears()));
        //减分
        preMuBenefitEvaluationVo.setSubList(preMuImportSubstractMapper.getUscc(preMuBenefitEvaluationVo.getUscc(),preMuBenefitEvaluationVo.getYears()));
        //否决项
        if(StringUtils.isNotNull(preMuBenefitEvaluationVo.getVetoItemIds())){
            List<PreMuImportVeto> vetoList= preMuImportVetoMapper.getByUscc(preMuBenefitEvaluationVo.getUscc());
            preMuBenefitEvaluationVo.setVetoList(vetoList);
        }
        //自定义指标
        List<PreMuImportCustomIndexLj> customIndexLjList= preMuImportCustomIndexLjMapper.getByCompanyId(preMuBenefitEvaluationVo.getCompanyId());
        if(customIndexLjList!=null&&customIndexLjList.size()>0){
            preMuBenefitEvaluationVo.setCustomIndexLjList(customIndexLjList);
        }
        return success(preMuBenefitEvaluationVo);
    }

    /**
     * 新增亩产效益评价
     */
    @RequiresPermissions("premu:evaluation:add")
    @Log(title = "亩产效益评价", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PreMuBenefitEvaluation preMuBenefitEvaluation)
    {
        return toAjax(preMuBenefitEvaluationService.insertPreMuBenefitEvaluation(preMuBenefitEvaluation));
    }

    /**
     * 修改亩产效益评价
     */
    @RequiresPermissions("premu:evaluation:edit")
    @Log(title = "亩产效益评价", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PreMuBenefitEvaluation preMuBenefitEvaluation)
    {
        return toAjax(preMuBenefitEvaluationService.updatePreMuBenefitEvaluation(preMuBenefitEvaluation));
    }

    /**
     * 删除亩产效益评价
     */
    @RequiresPermissions("premu:evaluation:remove")
    @Log(title = "亩产效益评价", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(preMuBenefitEvaluationService.deletePreMuBenefitEvaluationByIds(ids));
    }

    @PostMapping("/addAppeal")
    public AjaxResult addAppeal(@RequestBody PreMuAppealDto[] appealDtos){

        if(StringUtils.isNotNull(appealDtos[0].getBenefitEvaluationId())&&
                StringUtils.isNotNull(appealDtos[0].getCompanyId())&&
                StringUtils.isNotNull(appealDtos[0].getField())&&
                StringUtils.isNotNull(appealDtos[0].getFieldName())&&
                StringUtils.isNotNull(appealDtos[0].getCurrValue())&&
                StringUtils.isNotNull(appealDtos[0].getShouldValue())){


            String id= IdUtils.simpleUUID();
            PreMuBenefitEvaluationAppeal preMuBenefitEvaluationAppeal=new PreMuBenefitEvaluationAppeal();

            int flag=0;
            preMuBenefitEvaluationAppeal.setBenefitEvaluationId(appealDtos[0].getBenefitEvaluationId());
            preMuBenefitEvaluationAppeal.setCompanyId(appealDtos[0].getCompanyId());
            preMuBenefitEvaluationAppeal.setStatus("0");
            List<PreMuBenefitEvaluationAppeal> appealList= preMuBenefitEvaluationAppealService.selectPreMuBenefitEvaluationAppealList(preMuBenefitEvaluationAppeal);
           if(appealList!=null&&appealList.size()>0){
                return  warn("当前有申诉未完成处理，请处理完后再进行申诉！");
            }else{
                preMuBenefitEvaluationAppeal.setId(id);
                preMuBenefitEvaluationAppeal.setStatus("0");
                preMuBenefitEvaluationAppeal.setCompanyId(appealDtos[0].getCompanyId());
                preMuBenefitEvaluationAppeal.setCreateTime(new Date());
                preMuBenefitEvaluationAppeal.setBenefitEvaluationId(appealDtos[0].getBenefitEvaluationId());
                preMuBenefitEvaluationAppeal.setHandleTime(new Date());
                flag= preMuBenefitEvaluationAppealService.insertPreMuBenefitEvaluationAppeal(preMuBenefitEvaluationAppeal);
             }

            for (int i = 0; i < appealDtos.length; i++) {
                PreMuBenefitEvaluationAppealDetails preMuBenefitEvaluationAppealDetails=new PreMuBenefitEvaluationAppealDetails();
                preMuBenefitEvaluationAppealDetails.setAppealId(id);
                preMuBenefitEvaluationAppealDetails.setField(appealDtos[i].getField());
                preMuBenefitEvaluationAppealDetails.setFieldName(appealDtos[i].getFieldName());
                preMuBenefitEvaluationAppealDetails.setCurrValue(appealDtos[i].getCurrValue());
                List<PreMuBenefitEvaluationAppealDetails> detailsList=
                        preMuBenefitEvaluationAppealDetailsService.selectPreMuBenefitEvaluationAppealDetailsList(preMuBenefitEvaluationAppealDetails);
                if(detailsList!=null&&detailsList.size()>0){
                    logger.info("重复数据添加！");
                }else{
                    preMuBenefitEvaluationAppealDetails.setId(IdUtils.simpleUUID());
                    preMuBenefitEvaluationAppealDetails.setStatus("0");
                    preMuBenefitEvaluationAppealDetails.setCurrValue(appealDtos[i].getCurrValue());
                    preMuBenefitEvaluationAppealDetails.setAppealType(appealDtos[i].getAppealType());
                    preMuBenefitEvaluationAppealDetails.setShouldValue(appealDtos[i].getShouldValue());
                    preMuBenefitEvaluationAppealDetails.setDesc(appealDtos[i].getDesc());
                    preMuBenefitEvaluationAppealDetails.setFilePath(appealDtos[i].getFilePath());
                    preMuBenefitEvaluationAppealDetails.setYears(appealDtos[i].getYears());
                    preMuBenefitEvaluationAppealDetailsService.insertPreMuBenefitEvaluationAppealDetails(preMuBenefitEvaluationAppealDetails);
                }
            }

            PreMuBenefitEvaluationAppealDetails details=new PreMuBenefitEvaluationAppealDetails();
            //details.setAppealId(appealDtos[0].getBenefitEvaluationId());
            details.setAppealId(appealDtos[0].getBenefitEvaluationId());
            List<PreMuBenefitEvaluationAppealDetails> list=
                    preMuBenefitEvaluationAppealDetailsService.selectPreMuBenefitEvaluationAppealDetailsList(details);

            return  success(list);
        }else{
            return  warn("缺少参数字段！");
        }
    }

    /**
     * 导出详情
     * @param id
     * @param resp
     * @throws IOException
     * @throws TemplateException
     */
    @GetMapping("/detail/export/{id}")
    void detailExport(@PathVariable("id") String id, HttpServletResponse resp) throws IOException, TemplateException, freemarker.template.TemplateException {
        Map<String, Object> dataMap = new HashMap<>();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        PreMuBenefitEvaluationVo PreMuBenefitEvaluationVo = preMuBenefitEvaluationService.getById(id);
        PreMuCompanyInfo companyInfo = new PreMuCompanyInfo();
        if(StringUtils.isNotNull(PreMuBenefitEvaluationVo.getCompanyId())){
            companyInfo= preMuCompanyInfoService.getById(PreMuBenefitEvaluationVo.getCompanyId());
        }
        Date fillTableDate = PreMuBenefitEvaluationVo.getFillTableDate();
        Date evaluationDate = PreMuBenefitEvaluationVo.getEvaluationDate();
        int rowSize = 54 + 10; //表格行数，预留10行
        if (fillTableDate != null) {
            dataMap.put("fillTableDate", df.format(fillTableDate));
        }
        if (evaluationDate != null) {
            dataMap.put("evaluationDate", df.format(evaluationDate));
        }
        String companyType =null;
        if(StringUtils.isNotNull(PreMuBenefitEvaluationVo.getCompanyType())){
            if("1".contains(PreMuBenefitEvaluationVo.getCompanyType())){
                companyType="规上企业";
            }else{
                companyType="规下企业";
            }
        }
        dataMap.put("companyType", companyType);
        dataMap.put("mcBenefitEvaluation", PreMuBenefitEvaluationVo);
        dataMap.put("companyInfoDO", companyInfo);
        if(StringUtils.isNotNull(PreMuBenefitEvaluationVo.getIndustryType())){
            dataMap.put("hyName", PreMuBenefitEvaluationVo.getIndustryType());
        }
        if(StringUtils.isNotNull(PreMuBenefitEvaluationVo.getCompanyProp())){
            dataMap.put("companyProp", PreMuBenefitEvaluationVo.getCompanyProp());
        }
        //获取当前企业对应的指标权重
        Map<String, Object> params = new HashMap<>();
        params.put("county", companyInfo.getCounty());
        params.put("companyType", PreMuBenefitEvaluationVo.getCompanyType());
        //自定义指标
        Map<String, Object> indicatorMap = this.queryCustormIndicatorValue(Integer.valueOf(PreMuBenefitEvaluationVo.getYears()), PreMuBenefitEvaluationVo.getCompanyId(),
                companyInfo);
        dataMap.put("indicatorMap", indicatorMap);
        //加减分项和否决项
        List<Map<String, Object>> addItemDOList = new ArrayList<>();
        List<Map<String, Object>> substractItemDOList = new ArrayList<>();
        List<PreMuReject> vetoItemDOlist = new ArrayList<PreMuReject>();
        String substractItemIds = PreMuBenefitEvaluationVo.getSubstractItemIds();
        String vetoItemIds = PreMuBenefitEvaluationVo.getVetoItemIds();
        LocalDate localDate = LocalDate.now();
        PreMuImportAdd preMuImportAdd =new PreMuImportAdd();
        preMuImportAdd.setCounty(companyInfo.getCounty());
        preMuImportAdd.setYear(String.valueOf(localDate.getYear() - 1));
        preMuImportAdd.setUscc(companyInfo.getUscc());
        //加分
        List<PreMuImportAddVo> addSubstractList=  preMuImportAddMapper.getAddList(preMuImportAdd);
        for (int i = 0; i < addSubstractList.size(); i++) {
            Map<String, Object> addItem = new HashMap<>();
            addItem.put("id", addSubstractList.get(i).getItemId());
            addItem.put("names", addSubstractList.get(i).getItemNames());
            addItem.put("score", addSubstractList.get(i).getItemScore());
            addItem.put("desc", addSubstractList.get(i).getItemDesc());
            addItemDOList.add(addItem);
        }
        //减分
        PreMuImportAddSubstract substract =new PreMuImportAddSubstract();
        substract.setCounty(companyInfo.getCounty());
        substract.setYear(String.valueOf(localDate.getYear() - 1));
        substract.setUscc(companyInfo.getUscc());
        List<PremuImportAddSubstractVo> substractVoList= preMuImportAddSubstractMapper.getAddSubstractVoList(substract);
        String fileName = PreMuBenefitEvaluationVo.getCompanyName() + PreMuBenefitEvaluationVo.getUscc() + ".xls";
        for (int i = 0; i < substractVoList.size(); i++) {
            Map<String, Object> addItem = new HashMap<>();
            addItem.put("id", addSubstractList.get(i).getItemId());
            addItem.put("names", addSubstractList.get(i).getItemNames());
            addItem.put("score", addSubstractList.get(i).getItemScore());
            addItem.put("desc", addSubstractList.get(i).getItemDesc());
            substractItemDOList.add(addItem);
        }

        if (StringUtils.isNotEmpty(vetoItemIds)) {
            String[] vetoItemIdArr = vetoItemIds.split(",");
            if (vetoItemIdArr.length > 0) {
                for (int i = 0; i < vetoItemIdArr.length; i++) {
                    PreMuReject vetoItemDO = preMuRejectService.selectPreMuRejectById(vetoItemIdArr[i]);
                    if (vetoItemDO != null && !"0".equals(vetoItemDO.getDelFlag())) {
                        vetoItemDO.setRejectName(vetoItemDO.getRejectName() + "--(该指标已删除)");
                    }
                    vetoItemDOlist.add(vetoItemDO);
                }
            }
        }
        dataMap.put("addItemDOList", addItemDOList);
        dataMap.put("substractItemDOList", substractItemDOList);

        rowSize += addItemDOList.size() + substractItemDOList.size() + vetoItemDOlist.size();
        dataMap.put("rowSize", rowSize);
        FreemarkerUtil.downlaodGenerateFile("evaluate.ftl", dataMap, resp, fileName);

    }

    private Map<String, Object> queryCustormIndicatorValue(Integer year, String companyId,PreMuCompanyInfo companyInfo) {

        Map<String, Object> returnMap = new HashMap<String, Object>();
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> indicatorParamMap = new HashMap<String, Object>();
        PreMuCustomIndicator cus=new PreMuCustomIndicator();
        cus.setCounty(companyInfo.getCounty());
        LocalDate localDate = LocalDate.now();
        cus.setYear(String.valueOf(localDate.getYear() - 1));
        cus.setCompanyType(companyInfo.getCompanyType());
        PreMuImportCustomIndexLj indexLj=new PreMuImportCustomIndexLj();
        indexLj.setYear(String.valueOf(localDate.getYear() - 1));
        indexLj.setEnterId(companyId);

        List<PreMuImportCustomIndexLjVo> indicatorValueDOList= preMuCustomIndicatorService.getIndexLjVoList(indexLj);
        if (indicatorValueDOList != null && !indicatorValueDOList.isEmpty()) {
            for (int i = 0; i < indicatorValueDOList.size(); i++) {
                resultMap = new HashMap<String, Object>();
                returnMap.put("id", indicatorValueDOList.get(i).getId());
                returnMap.put("companyId", indicatorValueDOList.get(i).getCompanyId());
                returnMap.put("year", indicatorValueDOList.get(i).getYears());
                resultMap.put("name", indicatorValueDOList.get(i).getIndexName());
                resultMap.put("unit", indicatorValueDOList.get(i).getUnit());
                resultMap.put("code", indicatorValueDOList.get(i).getCode());
                if(indicatorValueDOList.get(i).getIndexValue()!=null){
                    resultMap.put("value", indicatorValueDOList.get(i).getIndexValue());
                }else{
                    resultMap.put("value", 0);
                }
            }
            resultList.add(resultMap);
        }
        if (!returnMap.containsKey("id")) {
            returnMap.put("id", "");
        }
        returnMap.put("indicatorList", resultList);
        return returnMap;
    }

    /**
     * <p>
     *     一键试算<br/>
     *     获取试用统计信息
     * </p>
     * @param preMuBenefitEvaluation companyType 企业类型
     * @return 平均值 中位数 区域指标
     */
    @GetMapping("/getTrialStatistics")
    public AjaxResult getTrialStatistics(PreMuBenefitEvaluationDto preMuBenefitEvaluation){
        return preMuBenefitEvaluationService.getTrialStatistics(preMuBenefitEvaluation);
    }

    @RequiresPermissions("premu:evaluation:editall")
    @Log(title = "一键核实", businessType = BusinessType.UPDATE)
    @PutMapping("/editAll")
    public AjaxResult editAll( PreMuBenefitEvaluation preMuBenefitEvaluation)
    {
        return toAjax( preMuBenefitEvaluationService.editAll(preMuBenefitEvaluation));
    }


    /**
     * <p>
     *     一键试算
     * </p>
     * <p>
     *      获取企业的单项指标值
     * </p>
     * @param preMuBenefitEvaluation
     * @return
     */
    @GetMapping("/getEnterSingleIndexScore")
    public TableDataInfo getEnterSingleIndexScore(PreMuBenefitEvaluationDto preMuBenefitEvaluation){
        startPage();
        if(StringUtils.isBlank(preMuBenefitEvaluation.getCompanyType())){
            preMuBenefitEvaluation.setCompanyType("1");
        }
        preMuBenefitEvaluation.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
        LocalDate localDate = LocalDate.now();
        preMuBenefitEvaluation.setYears(String.valueOf(localDate.getYear() - 1));
        return getDataTable(preMuBenefitEvaluationService.getEnterSingleIndexScore(preMuBenefitEvaluation));
    }

    /**
     * 应用
     * @param params
     * @return
     */
    @PostMapping("/adhibition")
    public AjaxResult adhibition(@RequestBody PreMuBenefitEvaluationDto params){

        if(StringUtils.isBlank(params.getCompanyType())){
            return AjaxResult.warn("请选择企业类型");
        }
        params.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
        LocalDate localDate = LocalDate.now();
        params.setYears(String.valueOf(localDate.getYear() - 1));
        
        //设置区县
        String district = SecurityUtils.getLoginUser().getSysUser().getDistrict();
        params.setCounty(district);
        return preMuBenefitEvaluationService.adhibition(params);
    }

    @PostMapping("/rate")
    public AjaxResult rate(String year, String companyType, @RequestParam(value="park", required = false) String park, @RequestParam(value="industry", required = false) String industry){

        PreMuImportBenefitEvaluationNo preMuImportBenefitEvaluationNo = new PreMuImportBenefitEvaluationNo();
        preMuImportBenefitEvaluationNo.setYear(Long.valueOf(year));
        preMuImportBenefitEvaluationNo.setCompanyType(companyType);
        preMuImportBenefitEvaluationNo.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
        List<PreMuImportBenefitEvaluationNo> preMuImportBenefitEvaluationNos = preMuImportBenefitEvaluationNoMapper.listEvaNO(preMuImportBenefitEvaluationNo);

        if(preMuImportBenefitEvaluationNos != null && !preMuImportBenefitEvaluationNos.isEmpty()){
            List<String> noBenefitEvaluationIds = preMuImportBenefitEvaluationNos.stream().map(PreMuImportBenefitEvaluationNo::getId).collect(Collectors.toList());
            preMuImportBenefitEvaluationNoMapper.updateNoEvaluationById(noBenefitEvaluationIds);
        }
        return preMuBenefitEvaluationService.evaluate(year,companyType,SecurityUtils.getLoginUser().getSysUser().getDistrict(), park, industry);
    }
    /***
     * 结果比例
     */
    @GetMapping(value = "/getProportion")
    public AjaxResult getProportion(PreMuBenefitEvaluation preMuBenefitEvaluation)
    {
        PreMuGradingRatioVo  p=preMuBenefitEvaluationService.getGradingRatioVo(preMuBenefitEvaluation);

        // 将字符串类型的数字转换为BigDecimal对象
        if(StringUtils.isNotNull(p.getSumA())&&StringUtils.isNotNull(p.getSumB())&&
                StringUtils.isNotNull(p.getSumC())&&StringUtils.isNotNull(p.getSumD())){
            BigDecimal sumA = new BigDecimal(p.getSumA());
            BigDecimal sumB = new BigDecimal(p.getSumB());
            BigDecimal sumC = new BigDecimal(p.getSumC());
            BigDecimal sumD = new BigDecimal(p.getSumD());
            // 计算sumA除以(sumA+sumB+sumC)
            BigDecimal sumTotal = sumA.add(sumB).add(sumC).add(sumD);
            if (sumTotal.compareTo(BigDecimal.ZERO) == 0) {
            }else{
                BigDecimal resultA = sumA.divide(sumTotal, 2, BigDecimal.ROUND_HALF_UP); // 将结果保留两位小数
                BigDecimal resultB = sumB.divide(sumTotal, 2, BigDecimal.ROUND_HALF_UP); // 将结果保留两位小数
                BigDecimal resultC = sumC.divide(sumTotal, 2, BigDecimal.ROUND_HALF_UP); // 将结果保留两位小数
                BigDecimal resultD = sumD.divide(sumTotal, 2, BigDecimal.ROUND_HALF_UP); // 将结果保留两位小数
                // 将结果乘以100
                resultA = resultA.multiply(new BigDecimal("100"));
                resultB = resultB.multiply(new BigDecimal("100"));
                resultC = resultC.multiply(new BigDecimal("100"));
                resultD = resultD.multiply(new BigDecimal("100"));

                p.setProportionA(String.valueOf(resultA));
                p.setProportionB(String.valueOf(resultB));
                p.setProportionC(String.valueOf(resultC));
                p.setProportionD(String.valueOf(resultD));
            }

        }
        return success(p);
    }

    /***
     * 上报封存
     */
    @GetMapping(value = "/reporting")
    public AjaxResult reporting( PreMuBenefitEvaluation preMuBenefitEvaluation)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Set<String> roles= loginUser.getRoles();
        List<PreMuBenefitEvaluation> list=new ArrayList<>();
        if(roles.contains("x_01_011")||roles.contains("along_yellow_river")){
            String county=  loginUser.getSysUser().getDistrict();
            preMuBenefitEvaluation.setCounty(county);
            preMuBenefitEvaluation.setStatus("4");
              list = preMuBenefitEvaluationService.selectPreMuBenefitEvaluationList(preMuBenefitEvaluation);
              if(list.size()>0){
                  List<String> idsList=list.stream().map(PreMuBenefitEvaluation::getId).collect(Collectors.toList());
                  preMuBenefitEvaluationService.updateStatusByIds(idsList);
              }else{
                  return warn("已上报封存过数据！");
              }
        }else{
            return warn("无权进行此操作!");
        }
        return success("上报封存"+list.size()+"条数据！");
    }
    /***
     *  一键核实
     */
    @GetMapping(value = "/verify")
    public AjaxResult verify( PreMuBenefitEvaluation preMuBenefitEvaluation)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Set<String> roles= loginUser.getRoles();
        if(roles.contains("x_01_011")||roles.contains("along_yellow_river")){
            String county=  loginUser.getSysUser().getDistrict();
            preMuBenefitEvaluation.setCounty(county);

            LocalDate localDate = LocalDate.now();
            preMuBenefitEvaluation.setYears(String.valueOf(localDate.getYear() - 1));

            List<PreMuBenefitEvaluation> list = preMuBenefitEvaluationService.selectPreMuBenefitEvaluationHsList(preMuBenefitEvaluation);
            List<String> idsList=list.stream().map(PreMuBenefitEvaluation::getId).collect(Collectors.toList());
            preMuBenefitEvaluationService.updateVerifyByIds(idsList);
        }else{
            return warn("无权进行此操作!");
        }
        return success("操作成功！");
    }

    /**
     * 取消评级
     * @return
     */
    @PostMapping("/grade")
    public AjaxResult grade(@RequestBody PreMuChartsDto chartsDto){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Set<String> roles= loginUser.getRoles();
        if(roles.contains("x_01_011")||roles.contains("along_yellow_river")){
            String county=  loginUser.getSysUser().getDistrict();
            chartsDto.setCounty(county);
        }else if(roles.contains("s_01_011")){
            String city=  loginUser.getSysUser().getCity();
            chartsDto.setCity(city);
        }else if(roles.contains("p_01_011")){
            String province=  loginUser.getSysUser().getProvince();
            chartsDto.setProvince(province);
        }
        return preMuBenefitEvaluationService.grade(chartsDto);
    }

    /**
     * 升档降档
     * @param params
     * @return
     */
    @PostMapping("/changeLevel")
    public AjaxResult changeLevel(@RequestBody Map<String,String> params){
        return preMuBenefitEvaluationService.changeLevel(params);
    }

    /**
     * 查询企业升降档记录
     * @param companyId
     * @return
     */
    @GetMapping("/queryLevelLog")
    public TableDataInfo queryLevelLog(@RequestParam("companyId") String companyId,@RequestParam("years") String years){
        startPage();
        List<PreMuBenefitEvaluationLog> r = preMuBenefitEvaluationService.queryLevelLog(companyId,years);
        return getDataTable(r);
    }

    /**
     * 查询升档降档后的详情信息
     * @param id
     * @return
     */
    @GetMapping("/queryUpDownDetailInfo/{id}")
    public AjaxResult queryUpDownDetailInfo(@PathVariable("id") String id){
        PreMuBenefitEvaluationLog result = preMuBenefitEvaluationService.queryUpDownDetailInfo(id);
        return AjaxResult.success(result);
    }

    /**
     * <p>
     *     查询白名单的基础数据，
     *     数据来源亩产
     * </p>
     * @return
     */
    @GetMapping("/queryWhiteCompanyInfoByUscc/{id}")
    public AjaxResult queryWhiteCompanyInfoById(@PathVariable("id") String id){
        EmEnterpriseInformationCollection r = preMuBenefitEvaluationService.queryWhiteCompanyInfoById(id);
        return AjaxResult.success(r);
    }

    @Autowired
    private PreMuCompanyInfoMapper preMuCompanyInfoMapper;

    /**
     * 下载亩产评价结果数据
     */
    @GetMapping("/downBenefitEvaluationInfo/{id}")
    public void downBenefitEvaluationInfo(@PathVariable("id")String id,HttpServletResponse response){

        String templatePath = "/Users/sangguangcan/Desktop/pre_template.xlsx";
        String templatePath1 = "/Users/sangguangcan/Desktop/pre_template1.xlsx";

        PreMuBenefitEvaluation preMuBenefitEvaluation = preMuBenefitEvaluationMapper.selectPreMuBenefitEvaluationById(id);
        if(preMuBenefitEvaluation == null){
            //一期中如果参评企业数据为空，会查询不参评的企业
            //二期中评价结果中不显示不参评企业，所以这里做为预留
            throw new RuntimeException("没有查询到企业信息");
        }
        //通过亩产评价结果中的企业Id查询企业基本信息表的中数据
        PreMuCompanyInfo preMuCompanyInfo = preMuCompanyInfoMapper.selectPreMuCompanyInfoById(preMuBenefitEvaluation.getCompanyId());
        if(preMuCompanyInfo == null){
            //这里处理和上面的亩产评价结果中一样
            throw new RuntimeException("没有查询到企业信息");
        }

        PreMuBenefitEvaluationTemplateVo templateParams = new PreMuBenefitEvaluationTemplateVo();

        templateParams.setLevel(preMuBenefitEvaluation.getMjLevel());
        templateParams.setYears(preMuBenefitEvaluation.getYears());
        templateParams.setCompanyName(preMuCompanyInfo.getCompanyName());
        templateParams.setUscc(preMuCompanyInfo.getUscc());
        if(StringUtils.isNotBlank(preMuCompanyInfo.getCompanyType())){
            templateParams.setCompanyType(StringUtils.equals(preMuCompanyInfo.getCompanyType(),"1") ? "规上企业" : "规下企业");
        }
        templateParams.setDetailAddr(preMuCompanyInfo.getDetailAddr());

        try(
                ServletOutputStream outputStream = response.getOutputStream();
                ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(templatePath).build()
                ){
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            excelWriter.fill(templateParams,writeSheet);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @GetMapping("/getExportCounts")
    public AjaxResult getExportCounts(){

        LoginUser loginUser = SecurityUtils.getLoginUser();
        Set<String> roles= loginUser.getRoles();
        if(roles.contains("x_01_011")||roles.contains("along_yellow_river")||roles.contains("s_01_011")){
            PreMuExportCounts preMuExportCounts= preMuExportCountsService.selectOne(loginUser.getUserid());
            if(preMuExportCounts!=null){
                if(preMuExportCounts.getCounts().contains("6")){
                    return AjaxResult.success(false);
                }else {
                    return AjaxResult.success(true);
                }
            }else{
                return AjaxResult.success(true);
            }
        }else if(roles.contains("s_01_011")){
            return AjaxResult.success(false);
        }else if(roles.contains("p_01_011")){
            return AjaxResult.success(true);
        }else if(roles.contains("admin")){
            return AjaxResult.success(true);
        }else if(roles.contains("q_01_001")){
            return AjaxResult.success(false);
        }
        return AjaxResult.success(false);
    }



    /**
     * 亩产效益评价确认表导出
     */
    @Log(title = "评价确认表导出", businessType = BusinessType.EXPORT)
    @PostMapping("/exportPreMuBenefitEvaluation")
    public void exportPreMuBenefitEvaluation(HttpServletResponse response, @RequestBody PreMuBenefitEvaluation preMuBenefitEvaluation) throws UnsupportedEncodingException  {
        try {

            LocalDate localDate = LocalDate.now();
            preMuBenefitEvaluation.setYears(String.valueOf(localDate.getYear() - 1));

            // 2023年及以前
            List<PreMuBenefitEvaluation> list2023 = new ArrayList<>();
            // 2024年及以后
            List<PreMuBenefitEvaluation20250520> list = new ArrayList<>();
            //如果不是数据，说明是在亩产大屏里面跳转过来的
            if (org.apache.commons.lang3.StringUtils.isNotBlank(preMuBenefitEvaluation.getCity()) && !NumberUtil.isNumber(preMuBenefitEvaluation.getCity())) {
                String cityCode = sysAreaMapper.selectCodeByAreaName(preMuBenefitEvaluation.getCity());
                preMuBenefitEvaluation.setCity(cityCode);
            }
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if(loginUser!=null) {
                Set<String> roles = loginUser.getRoles();
                if (roles.contains("x_01_011") || roles.contains("along_yellow_river")) {
                    String county = loginUser.getSysUser().getDistrict();
                    preMuBenefitEvaluation.setCounty(county);
                } else if (roles.contains("s_01_011")) {
                    // 直接抛出异常
                    throw new RuntimeException("您没有权限进行此操作");
                }
            }
            if (preMuBenefitEvaluation != null) {
                if (StringUtils.isNotNull(preMuBenefitEvaluation.getDataType())) {
                    if ("1".equals(preMuBenefitEvaluation.getDataType())) {
//                        list = preMuBenefitEvaluationService.selectPreMuBenefitEvaluationList(preMuBenefitEvaluation);
                        if(this.before2024Year(preMuBenefitEvaluation.getYears())) {
                            list2023 = preMuBenefitEvaluationMapper.selectPreMuBenefitEvaluationExporetList(preMuBenefitEvaluation);
                            this.setBefore2024Data(list2023);
                        }else {
                            list = preMuBenefitEvaluationMapper2025.selectPreMuBenefitEvaluationExporetList(preMuBenefitEvaluation);
                            this.setAfter2024Data(list);
                        }
                    } else if ("2".equals(preMuBenefitEvaluation.getDataType())) {
                        if(this.before2024Year(preMuBenefitEvaluation.getYears())) {
                            list2023 = preMuBenefitEvaluationNoMapper.selectNoExportList(preMuBenefitEvaluation);
                            if (list2023 != null && list2023.size() > 0) {
                                for (PreMuBenefitEvaluation p : list2023) {
                                    p.setDataType("2");
                                }
                            }
                        }
                        else {
                            list = preMuBenefitEvaluationMapper2025.selectNoExportList(preMuBenefitEvaluation);
                            if (list != null && list.size() > 0) {
                                for (PreMuBenefitEvaluation20250520 p : list) {
                                    p.setDataType("2");
                                }
                            }
                        }
                    }
                } else {
                    preMuBenefitEvaluation.setDataType("1");
                    if(this.before2024Year(preMuBenefitEvaluation.getYears())) {
                        list2023 = preMuBenefitEvaluationService.selectPreMuBenefitEvaluationList(preMuBenefitEvaluation);
                        if (list2023 != null && list2023.size() > 0) {
                            for (PreMuBenefitEvaluation p : list2023) {
                                p.setDataType("1");
                            }
                        }
                    }
                    else {
                        list = preMuBenefitEvaluationService.selectPreMuBenefitEvaluationList2025(preMuBenefitEvaluation);
                        if (list != null && list.size() > 0) {
                            for (PreMuBenefitEvaluation20250520 p : list) {
                                p.setDataType("1");
                            }
                        }
                    }
                }
                String companyType = StringUtils.equals("1",preMuBenefitEvaluation.getCompanyType()) ? "规上企业" : "规下企业";
                // 2025年修改了模板的列，去掉了大部分税收，部分列改名
                if(this.before2024Year(preMuBenefitEvaluation.getYears())) {
                    preMuBenefitEvaluationService.getPreMuBenefitEvaluationExcel(response, list2023,companyType);
                }
                else {
                    preMuBenefitEvaluationService2025.getPreMuBenefitEvaluationExcel(response, list,companyType);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出异常！");

        }
    }

    private boolean before2024Year(String year) {
        if(StringUtils.isEmpty(year)) {
            throw new RuntimeException("年份不能为空！");
        }
        return Integer.parseInt(year) < 2024;
    }

    // 2024年之前的数据设置
    private void setBefore2024Data(List<PreMuBenefitEvaluation> list) {
        if(CollectionUtil.isEmpty(list)) {
            return;
        }
        //加载列表中企业的自定义指标分数
        List<String> ids = list.stream().map(PreMuBenefitEvaluation::getCompanyId).collect(Collectors.toList());
        List<PreMuImportCustomIndexLj> byCompanyIds = preMuImportCustomIndexLjMapper.getByCompanyIds(ids);
        Map<String, List<PreMuImportCustomIndexLj>> collect = new HashMap<>(128);
        if(byCompanyIds != null && !byCompanyIds.isEmpty()){
            collect = byCompanyIds.stream().collect(Collectors.groupingBy(PreMuImportCustomIndexLj::getEnterId));
        }

        for (PreMuBenefitEvaluation p : list) {
            p.setDataType("1");
            List<PreMuImportCustomIndexLj> preMuImportCustomIndexLjs = collect.get(p.getCompanyId());
            if(preMuImportCustomIndexLjs != null && !preMuImportCustomIndexLjs.isEmpty()){
                BigDecimal zbSum = preMuImportCustomIndexLjs.stream().map(k -> {
                    BigDecimal bigDecimal = new BigDecimal(0);
                    if (StringUtils.isNotBlank(k.getIndexValue())) {
                        bigDecimal = new BigDecimal(k.getIndexValue());
                    }
                    return bigDecimal;
                }).reduce(BigDecimal::add).get();
                p.setZdyzbCScore(zbSum);
            }
            BigDecimal addScore = p.getAddScore() == null ? BigDecimal.ZERO : p.getAddScore();
            BigDecimal subScore = p.getSubScore() == null ? BigDecimal.ZERO : p.getSubScore();
            BigDecimal zdyzbScore= p.getZdyzbCScore() == null ? BigDecimal.ZERO : p.getZdyzbCScore();

            if(zdyzbScore.compareTo(BigDecimal.ZERO) == 0){
                BigDecimal jg = addScore.subtract(subScore);
                p.setZdyzbCScore(jg);
            }else {
                BigDecimal jg = zdyzbScore.add(addScore).subtract(subScore);
                p.setZdyzbCScore(jg);
            }

        }

    }

    // 2024年及之后的数据设置
    private void setAfter2024Data(List<PreMuBenefitEvaluation20250520> list) {
        if(CollectionUtil.isEmpty(list)) {
            return;
        }
        //加载列表中企业的自定义指标分数
        List<String> ids = list.stream().map(PreMuBenefitEvaluation20250520::getCompanyId).collect(Collectors.toList());
        List<PreMuImportCustomIndexLj> byCompanyIds = preMuImportCustomIndexLjMapper.getByCompanyIds(ids);
        Map<String, List<PreMuImportCustomIndexLj>> collect = new HashMap<>(128);
        if(byCompanyIds != null && !byCompanyIds.isEmpty()){
            collect = byCompanyIds.stream().collect(Collectors.groupingBy(PreMuImportCustomIndexLj::getEnterId));
        }

        for (PreMuBenefitEvaluation20250520 p : list) {
            p.setDataType("1");
            List<PreMuImportCustomIndexLj> preMuImportCustomIndexLjs = collect.get(p.getCompanyId());
            if(preMuImportCustomIndexLjs != null && !preMuImportCustomIndexLjs.isEmpty()){
                BigDecimal zbSum = preMuImportCustomIndexLjs.stream().map(k -> {
                    BigDecimal bigDecimal = new BigDecimal(0);
                    if (StringUtils.isNotBlank(k.getIndexValue())) {
                        bigDecimal = new BigDecimal(k.getIndexValue());
                    }
                    return bigDecimal;
                }).reduce(BigDecimal::add).get();
                p.setZdyzbCScore(zbSum);
            }
            BigDecimal addScore = p.getAddScore() == null ? BigDecimal.ZERO : p.getAddScore();
            BigDecimal subScore = p.getSubScore() == null ? BigDecimal.ZERO : p.getSubScore();
            BigDecimal zdyzbScore= p.getZdyzbCScore() == null ? BigDecimal.ZERO : p.getZdyzbCScore();

            if(zdyzbScore.compareTo(BigDecimal.ZERO) == 0){
                BigDecimal jg = addScore.subtract(subScore);
                p.setZdyzbCScore(jg);
            }else {
                BigDecimal jg = zdyzbScore.add(addScore).subtract(subScore);
                p.setZdyzbCScore(jg);
            }

        }
    }

    @GetMapping("/getArea")
    public AjaxResult getArea(){
        String area="";
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(loginUser!=null) {
            Set<String> roles = loginUser.getRoles();
            if(roles.contains("x_01_011")||roles.contains("along_yellow_river")){
                String county=  loginUser.getSysUser().getDistrict();
                area=   sysAreaMapper.selectAreaNameByCode(county);
            }else if(roles.contains("s_01_011")){
                String city=  loginUser.getSysUser().getCity();
                area=sysAreaMapper.selectAreaNameByCode(city);
            }else if(roles.contains("p_01_011")){
                String province=  loginUser.getSysUser().getProvince();
                area=   sysAreaMapper.selectAreaNameByCode(province);
            }
        }
   ;
        return AjaxResult.success(area);
    }

    @GetMapping("/noDifferentCalType")
    public AjaxResult noDifferentCalType(PreMuBenefitEvaluationDto preMuBenefitEvaluation){
        if(StringUtils.isBlank(preMuBenefitEvaluation.getCompanyType())){
            preMuBenefitEvaluation.setCompanyType("1");
        }
        preMuBenefitEvaluation.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
        LocalDate localDate = LocalDate.now();
        preMuBenefitEvaluation.setYears(String.valueOf(localDate.getYear() - 1));
        return preMuBenefitEvaluationService.existDifferentCalType(preMuBenefitEvaluation);
    }
}
